#!/usr/bin/env python3
import os 
import sys 
# import zipfile_gbk
import src.zipfile_gbk as zipfile

def unzip_file(zip_filename):
    print("processing File " + zip_filename )
    file = zipfile.ZipFile(zip_filename, "r"); 
    for name in file.namelist(): 
        save_name = os.path.join(os.path.dirname(zip_filename), os.path.basename(os.path.splitext(zip_filename)[0]), name)
        pathname = os.path.dirname(save_name) 
        if not os.path.exists(pathname) and pathname !="":
            os.makedirs(pathname) 
        data = file.read(name); 
        if not os.path.exists(save_name):
            fo = open(save_name, "wb")
            fo.write(data)
            fo.close()
            print("[Extracting]:%s"%(name))
        else:
            print('[Exist]: %s'%(name))
    file.close() 


if __name__ == '__main__':

    if len(sys.argv) != 2:
        print("usage: %s <zip file|dir>"%sys.argv[0])
        sys.exit(-1)

    zip_filename = sys.argv[1]
    zip_filename = os.path.abspath(sys.argv[1]) 
    if os.path.isfile(zip_filename):
        unzip_file(zip_filename)
    elif os.path.isdir(zip_filename):
        files = os.listdir(zip_filename)
        for f in files:
            ft = os.path.join(zip_filename,f)
            if os.path.splitext(f)[1].lower() != '.zip' or not os.path.isfile(ft):
                continue
            unzip_file(os.path.join(zip_filename,f))